﻿using System;
using System.Net;
using System.Windows;
#if NETFX_CORE
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml;
#else
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
#endif

namespace UnitDriven.Controls
{
	public class WatermarkTextBox : Control
	{
		private TextBox text;
		private TextBlock watermark;

		public static readonly DependencyProperty TextProperty = DependencyProperty.Register(
			"Text", 
			typeof(string), 
			typeof(WatermarkTextBox), 
			new PropertyMetadata(null));

		public static readonly DependencyProperty WatermarkProperty = DependencyProperty.Register(
			"Watermark",
			typeof(string),
			typeof(WatermarkTextBox),
			new PropertyMetadata(""));

		public string Text
		{
			get { return (string)GetValue(TextProperty); }
			set { SetValue(TextProperty, value); }
		}

		public string Watermark
		{
			get { return (string)GetValue(WatermarkProperty); }
			set { SetValue(WatermarkProperty, value); }
		}

		public WatermarkTextBox()
		{
			this.DefaultStyleKey = typeof(WatermarkTextBox);
		}

#if NETFX_CORE
        protected override void OnApplyTemplate()
#else
		public override void OnApplyTemplate()
#endif
		{
			base.OnApplyTemplate();

			this.text = (TextBox)this.GetTemplateChild("text");
			this.watermark = (TextBlock)this.GetTemplateChild("watermark");

			this.text.TextChanged += (o, e) => this.OnTextChanged();
		}

		protected void OnTextChanged()
		{
			if (string.IsNullOrEmpty(text.Text))
				watermark.Visibility = Visibility.Visible;
			else
				watermark.Visibility = Visibility.Collapsed;

			if (this.TextChanged != null)
				this.TextChanged(this, EventArgs.Empty);
		}

		public event EventHandler TextChanged;
	}
}
